package com.module.circle.ui.schedule

import android.os.Bundle
import android.view.View
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.KeyEvents
import com.common.app.data.bean.circle.CircleListModel
import com.common.base.app.extras.getShowMsg
import com.common.base.app.extras.otherwise
import com.common.base.app.extras.setVisibility
import com.common.base.app.extras.showToast
import com.common.base.app.extras.startActivity
import com.common.base.app.extras.startActivityResultLauncher
import com.common.base.app.extras.yes
import com.common.base.app.fragment.BaseVMFragment
import com.common.base.utils.Page
import com.common.base.utils.StatusBarUtils
import com.common.base.utils.ViewUtils
import com.common.base.widget.animator.CustomAnimation1
import com.jeremyliao.liveeventbus.LiveEventBus
import com.module.circle.R
import com.module.circle.databinding.CircleFragmentSubCircieListBinding
import com.module.circle.ui.changeIntroduction.ChangeMyIntroductionActivity
import com.module.circle.ui.circleDetails.CircleDetailsActivity
import com.scwang.smart.refresh.header.ClassicsHeader
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener

/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：2025/07/23
 *
 * 描述：
 *
 * 修订历史：
 *
 */
class CircleListSubFragment :
    BaseVMFragment<CircleFragmentSubCircieListBinding, CircleViewModel>() {

    companion object {
        fun newInstance(mType: String): CircleListSubFragment {
            val fragment = CircleListSubFragment()
            fragment.mType = mType
            return fragment
        }

    }

    private var mType = ""

    private var page: Page = Page()

    private val mAdapter by lazy { CircleListSubItemAdapter(mType) }

    override fun getPlaceholderView() = mViewBinding.placeHolderView

    override fun getViewModel() = CircleViewModel::class.java

    override fun getViewBinding() = CircleFragmentSubCircieListBinding.inflate(layoutInflater)

    override fun initViews() {
        super.initViews()

        mViewBinding.hrv.setItemViewCacheSize(30)
        getRefreshFooter()?.let { mViewBinding.pdView.setRefreshFooter(it) }
        mViewBinding.pdView.setRefreshHeader(ClassicsHeader(requireActivity()))

        mAdapter.apply {
            adapterAnimation = CustomAnimation1()
            isAnimationFirstOnly = false
            mViewBinding.hrv.adapter = this
//            addFooterView(layoutInflater.inflate(R.layout.base_rlv_margin_footer_tr_view50, null))
            setOnItemChildClickListener(object : OnItemChildClickListener {
                override fun onItemChildClick(
                    adapter: BaseQuickAdapter<*, *>,
                    view: View,
                    position: Int
                ) {
                    if (ViewUtils.isFastClick()) return //防止多次点击
                    when (view.id) {
                        R.id.totalRoot -> {
                            val bundle = Bundle()
                            bundle.putParcelable(KeyBundle.BUNDLE_KEY, mAdapter.data[position])
                            bundle.putString(KeyBundle.EXPAND_DATA, mType)
                            requireActivity().startActivity<CircleDetailsActivity>(bundle, false)
                        }
                        R.id.tvRightBtn -> requestJoinCircles(mAdapter.data[position].id)
                    }
                }

            })
        }
    }

    override fun lazyInitData() {
        super.lazyInitData()
        showEmpty(getString(R.string.base_no_data2))
        initData()
    }

    override fun initEvents() {
        super.initEvents()
        setErrorRetryListener {
            lazyInitData()
        }

        mViewBinding.pdView.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onRefresh(refreshLayout: RefreshLayout) {
                refreshLayout.layout.postDelayed({
                    initData()
                }, 1000)
            }

            override fun onLoadMore(refreshLayout: RefreshLayout) {
                finishPdView()
            }
        })

        LiveEventBus.get(KeyEvents.KEY_CREATE_CIRCLE_EVENT).observe(this){
            initData()
        }
    }

    private fun initData() {
        page.reset()

//        val mList = mutableListOf<CircleListModel>()
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips2.baidu.com/it/u=2068760849,3022258785&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280",
//                name = "v是的V刹v",
//                describe = "昂首阔步呢",
//                membercount = 9
//            )
//        )
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips1.baidu.com/it/u=3885198370,1571719977&fm=3028&app=3028&f=JPEG&fmt=auto?w=2560&h=1920",
//                name = "VS",
//                describe = ""
//            )
//        )
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips2.baidu.com/it/u=658660608,3402622316&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960",
//                name = "A是的v",
//                describe = "可能可能能看见看看",
//                membercount = 19
//            )
//        )
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips3.baidu.com/it/u=3660856539,3077947179&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960",
//                name = "是的是的VS",
//                describe = "控件绝对是VS大v大v的是VSV刹大v那就看健康，吗， 你吗那么那么",
//                membercount = 119
//            )
//        )
//
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips2.baidu.com/it/u=2068760849,3022258785&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280",
//                name = "v是的V刹v",
//                describe = "昂首阔步呢",
//                membercount = 9
//            )
//        )
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips1.baidu.com/it/u=3885198370,1571719977&fm=3028&app=3028&f=JPEG&fmt=auto?w=2560&h=1920",
//                name = "VS",
//                describe = ""
//            )
//        )
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips2.baidu.com/it/u=658660608,3402622316&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960",
//                name = "A是的v",
//                describe = "可能可能能看见看看",
//                membercount = 19
//            )
//        )
//        mList.add(
//            CircleListModel(
//                imageurl = "http://gips3.baidu.com/it/u=3660856539,3077947179&fm=3028&app=3028&f=JPEG&fmt=auto?w=1280&h=960",
//                name = "是的是的VS",
//                describe = "控件绝对是VS大v大v的是VSV刹大v那就看健康，吗， 你吗那么那么",
//                membercount = 119
//            )
//        )
//        mAdapter.setList(mList.shuffled().take((3..8).random()))
//        showContent()

        setArticleData(if((getString(R.string.circle_recommendation_circle_hint) == mType)) "recommended"  else "joined")
    }

    private fun finishPdView() {
        mViewBinding.pdView.finishRefresh()
        mViewBinding.pdView.finishLoadMore()
    }


    private fun setArticleData(type:String) {
        showDialogLoading()
        mViewModel.getCirclesList(type) {
//            showToast(it.getShowMsg())
        }.observe(this) {
            mViewBinding.pdView.finishRefresh()
            it.isSuccess().yes {
                setVisibility(mViewBinding.notDataTotal, it.Data.isNullOrEmpty())
                mAdapter.setList(it.Data)
                showContent()
            }.otherwise {
                dismissLoadingDialog()
            }
        }
    }

    private fun requestJoinCircles(mId:Int) {
        if (mId <= 0) {
            showErrorMsg()
            return
        }
        showDialogLoading()
        mViewModel.requestJoinCircles(mId) {
            finishPdView()
        }.observe(this) {
            dismissLoadingDialog()
            it.isSuccess().yes {
                it.isSuccess().yes {
                    LiveEventBus.get(KeyEvents.KEY_CREATE_CIRCLE_EVENT).post(this)
                    showToast(R.string.circle_join_circle_completed_hint)
                }.otherwise {
                    showToast(it.Message)
                }
            }.otherwise {
                showToast(it.Message)
            }
        }
    }
}